package controllers
/*********************************************************/
/************本文档中的程序用于管理员相关的web操作*************/
/*********************version:1.0*************************/
/****Copyright (c) 2014年 许剑华. All rights reserved******/
/*********************************************************/
import (
	"encoding/json"
	"github.com/astaxie/beego"
	//"github.com/astaxie/beego/validation"
	"fmt"
	"time"
	//"log"
	//"smart_home/models"
	//"github.com/astaxie/beego/orm"
	m "smart_home/models"
	."smart_home/lib"
	"strconv"
	"github.com/astaxie/beego/validation"
	//"github.com/beego/samples/WebIM/models"
	//"github.com/astaxie/beego/validation"
)
type AdminController struct {
	beego.Controller
}

type DeviceStruct struct {
	Devices    []DeviceScript
}

type Test struct {
	Devices    string
}

type AppListType struct {
	RespCode			int
	Msg					string
	Count				int64
	List				[]m.NewVersionApp
}

var data_url string = beego.AppConfig.String("data_url")

//用于验证用户是否登入
func (this *AdminController)CheckAdminIsLogin()(bool,AdminSessionType){
	tel := this.Ctx.Input.Param(":tel")
	fmt.Println("tel",tel)
	var mAdminSessionType AdminSessionType
	if(tel == "") {
		return false,mAdminSessionType
	}else{
		data := this.GetSession(tel)
		fmt.Println("GetSession",data)

		if data == nil{
			return false,mAdminSessionType
		}else{
			mAdminSessionType = data.(AdminSessionType)
			fmt.Println("mAdminSessionType",mAdminSessionType)
			if mAdminSessionType.IsLogin == false{
				return false,mAdminSessionType
			}else{
				if((mAdminSessionType.LastDate.Unix() - time.Now().Unix()) > ONEDAY2SEC){
					return false,mAdminSessionType

				}else{
					return true,mAdminSessionType
				}
			}
		}
	}
}
/*********************************************************/
/************函数：SupervisoryOnlineDevice*****************/
/************功能：用于网页监控在线设备***********************/
/*********************************************************/
func (this *AdminController)SupervisoryOnlineDevice(){
//获取在线设备的列表
	devices_list :=GetOnlineDevice()
//	const list_len = len(devices_list)
	//fmt.Println("devices_list",devices_list)
//构建在线设备的列表的数据结构
	device_array  := DeviceStruct{make([]DeviceScript, len(devices_list))}
	var i int64 = 0
//	将在线设备的数据取出，放入DeviceStruct的结构体中
	for _,v:=range devices_list{
//		fmt.Println("k",k)
//		fmt.Println("v",v)
		device_array.Devices[i] = v
	}
//	fmt.Println("device_array",device_array)


	this.Data["json"] = &devices_list
	this.ServeJson();
}

/*********************************************************/
/************函数：Register********************************/
/************功能：注册新的管理员****************************/
/*********************************************************/
func (this *AdminController) Register() {
//	获取网页请求的方式
	method := this.Ctx.Input.Method()
	if method == "POST"{     //判断请求方式
		var u RegisterType
		var respone_json SiteResponeType
		err := this.ParseForm(&u)

		if err != nil {
			respone_json = SiteResponeType{SITE_PARA_ERROR,"参数有误",INVALIDS}
			this.Data["json"] = &respone_json
			this.ServeJson();
			return
		}
		_ ,err = m.GetAdminByTel(u.Tel)

		if err == nil{
			fmt.Println("err",err)
			respone_json = SiteResponeType{SITE_PARA_ERROR,"该用户已经存在",INVALIDS}
			this.Data["json"] = &respone_json
			this.ServeJson();
			return
		}else{
			user := m.Admin{Tel:u.Tel,UserName:u.UserName,UserPw:u.UserPw,Permission:0}
			_,err =m.AddAdmin(&user)
			fmt.Println("user:",user)
			if err != nil{
				fmt.Println("err",err)
				respone_json = SiteResponeType{SITE_PARA_ERROR,"用户添加失败",INVALID}
				this.Data["json"] = &respone_json
				this.ServeJson();
				return
			}
			respone_json = SiteResponeType{SITE_SUCCESS,INVALIDS,INVALIDS}
			this.Data["json"] = &respone_json
			this.ServeJson();
			return
		}
	}
}
/*********************************************************/
/************函数：Login********************************/
/************功能：管理员登入*******************************/
/*********************************************************/
func (this *AdminController) Login() {
	method := this.Ctx.Input.Method()

	if method == "POST"{
		//var respone_json Reg_Log_Type
		var mLoginType = new(LoginType)
		//this.ParseForm(&mLoginType)
		if err := this.ParseForm(mLoginType); err != nil {
			this.Data["error"] = "帐号或者密码错误"
			//this.ServeJson();
			this.TplNames = "admin-login.html"
		}
		fmt.Println("mLoginType",mLoginType)
		valid := validation.Validation{}
		b, err := valid.Valid(mLoginType)
		if err != nil {
			fmt.Println("error",err)
			this.Data["error"] = "系统故障"
			//this.ServeJson();
			this.TplNames = "admin-login.html"
			return
		}
		if !b {
			this.Data["error"] = "手机号格式有误"
			//this.ServeJson();
			this.TplNames = "admin-login.html"
			return
		}
		admin,err := m.GetAdminByTel(mLoginType.Tel)

		if err == nil{
			if admin.UserPw == Strtomd5(mLoginType.UserPw){
				//respone_json = Reg_Log_Type{SUCCESS,admin.Id,INVALID}
				data := this.GetSession(mLoginType.Tel)
				var mAdminSessionType AdminSessionType
				if data == nil{
					mAdminSessionType.LastDate = time.Now()
					mAdminSessionType.Count = 0
					mAdminSessionType.IsLogin = true
				}else{
					mAdminSessionType = data.(AdminSessionType)
					mAdminSessionType.IsLogin = true
					mAdminSessionType.LastDate = time.Now()
				}
				this.SetSession(admin.Tel,mAdminSessionType)
				this.Ctx.Redirect(302, "/admin/index/"+admin.Tel)
				return
				//this.ServeJson();
			}else{
				//respone_json = Reg_Log_Type{INVALID_PW,INVALID,INVALID}
				this.Data["error"] = "帐号或者密码错误"
				//this.ServeJson();
				this.TplNames = "admin-login.html"

				return
			}

		}else {
			fmt.Println("GetAdminByTel err",err)
			this.TplNames = "admin-login.html"

		}


	}else{
		this.TplNames = "admin-login.html"

	}
}
/*********************************************************/
/************函数：LoginOut********************************/
/************功能：管理员登出*******************************/
/*********************************************************/
func (this *AdminController) LoginOut() {
	tel := this.Ctx.Input.Param(":tel")
	if(tel == "") {
		this.Ctx.Redirect(302, "/admin/login")
	}else{
		data := this.GetSession(tel)
		var mAdminSessionType AdminSessionType
		if data == nil{
			this.Ctx.Redirect(302, "/admin/login")
			return
		}else{
			mAdminSessionType = data.(AdminSessionType)
			fmt.Println("mAdminSessionType",mAdminSessionType)
			if mAdminSessionType.IsLogin == false{
				this.Ctx.Redirect(302, "/admin/login")
				return
			}else{
					mAdminSessionType.IsLogin = false
					this.SetSession(tel,mAdminSessionType)
					this.Ctx.Redirect(302, "/admin/login")
					return
			}
		}
	}
}
/*********************************************************/
/************函数：Index**********************************/
/************功能：返回根目录*******************************/
/*********************************************************/
func (this *AdminController)Index(){
	tel := this.Ctx.Input.Param(":tel")
	if(tel == "") {
		this.Ctx.Redirect(302, "/admin/login")
	}else{
		data := this.GetSession(tel)
		var mAdminSessionType AdminSessionType
		if data == nil{
			this.Ctx.Redirect(302, "/admin/login")
			return
		}else{
			mAdminSessionType = data.(AdminSessionType)
			if mAdminSessionType.IsLogin == false{
				this.Ctx.Redirect(302, "/admin/login")
				return
			}else{
				if((mAdminSessionType.LastDate.Unix() - time.Now().Unix()) > ONEDAY2SEC){
					this.Ctx.Redirect(302, "/admin/login")
					return
				}
			}
		}
	}
	this.Data["tel"] = tel
	this.TplNames = "dashboard.html"

}

/*********************************************************/
/************函数：ShowDeviceConLog************************/
/************功能：返回设备控制的记录************************/
/********************************************************/
func (this *AdminController)ShowDeviceConLog(){
	tel := this.Ctx.Input.Param(":tel")    //从url中提取数据
	data := this.GetSession(tel)          //从session中提取数据
	var mAdminSessionType AdminSessionType
	if data == nil{                       //数据为空
		this.Ctx.Redirect(302, "/admin/login")
		return
	}else {
		mAdminSessionType = data.(AdminSessionType)    //数据格式转换
		if mAdminSessionType.IsLogin == false{
			this.Ctx.Redirect(302, "/admin/login")
			return
		}else {
			data, count := m.GetDeviceLog()
//			h, m, s := data[0].TimeStamp.Clock()
//			fmt.Println("data.TimeStamp", h, m, s)
//			fmt.Println("data.TimeStamp", data[0].TimeStamp)
//			fmt.Println("count", count)
//			this.Data["json"] = &data
//			this.ServeJson();
			this.Data["count"] = count
			this.Data["data"] = data
			this.TplNames = "users.html"
		}
	}
}
/*********************************************************/
/************函数：SetParticleSize*************************/
/************功能：设置控制服务器自我学习的时间粒度*************/
/********************************************************/
func (this *AdminController)SetParticleSize(){

	var	resp_data ResponeType
	mParticleSize,err := this.GetInt("ParticleSize")   //从表单中提取数据
	tel:= this.GetString("Tel")							//从表单中提取数据
	data := this.GetSession(tel)						//从session中提取数据
	var mAdminSessionType AdminSessionType
	if data == nil{                  //无该用户记录
		this.Ctx.Redirect(302, "/admin/login")
		return
	}else{
		mAdminSessionType = data.(AdminSessionType)
		if mAdminSessionType.IsLogin == false{
			this.Ctx.Redirect(302, "/admin/login")
			return
		}
	}
	if err != nil{
		resp_data = ResponeType{OPERATION_ERROR,INVALIDS,INVALID}
		this.Data["json"] = &resp_data
		this.ServeJson();
	}
	err = m.SetParticleSize(int(mParticleSize))
	if err != nil{
		resp_data = ResponeType{OPERATION_ERROR,INVALIDS,INVALID}
		this.Data["json"] = &resp_data
		this.ServeJson();
	}
	resp_data = ResponeType{SUCCESS,INVALIDS,INVALID}
	fmt.Println("mParticleSize",mParticleSize)
	this.Data["json"] = &resp_data
	this.ServeJson();
}


/*********************************************************/
/************函数：GetAdminList***************************/
/************功能：返回管理员的列表*************************/
/********************************************************/
func (this *AdminController)GetAdminList() {
	if islogin,_ := this.CheckAdminIsLogin();islogin == true {
		tel := this.Ctx.Input.Param(":tel")    //从url中提取数据
		data := this.GetSession(tel)          //从session中提取数据
		var mAdminSessionType AdminSessionType
		if data == nil {                       //数据为空
			var admins  interface{}
			this.Data["json"] = &admins
			this.ServeJson();
			return
		}else {
			mAdminSessionType = data.(AdminSessionType)    //数据格式转换
			if mAdminSessionType.IsLogin == false {
				var admins  interface{}
				this.Data["json"] = &admins
				this.ServeJson();
				return
			}else {
				if ((mAdminSessionType.LastDate.Unix()-time.Now().Unix()) > ONEDAY2SEC) {
					var admins  interface{}
					this.Data["json"] = &admins
					this.ServeJson();
					return
				}
			}
		}
		admins, _ := m.GetAdminList()
		this.Data["json"] = &admins
		this.ServeJson();
	}else{
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
}
/*********************************************************/
/************函数：AdminList******************************/
/************功能：返回管理员的页面*************************/
/********************************************************/
func (this *AdminController)AdminList() {
	if islogin,_ := this.CheckAdminIsLogin();islogin == true {
		tel := this.Ctx.Input.Param(":tel")          //从url中提取数据
		if tel == "" {                 //tel为空，重置浏览页面到登入页面
			this.Ctx.Redirect(302, "/admin/login")
			return
		}else {
			data := this.GetSession(tel)
			var mAdminSessionType AdminSessionType
			if data == nil {         //data为空，重置浏览页面到登入页面
				this.Ctx.Redirect(302, "/admin/login")
				return
			}else {                    //data为空，重置浏览页面到登入页面
				mAdminSessionType = data.(AdminSessionType)
				if mAdminSessionType.IsLogin == false {
					this.Ctx.Redirect(302, "/admin/login")
					return
				}else {
					if ((mAdminSessionType.LastDate.Unix()-time.Now().Unix()) > ONEDAY2SEC) {
						this.Ctx.Redirect(302, "/admin/login")
						return
					}
				}
			}
		}
		admin , _ := m.GetAdminByTel(tel)
		this.Data["tel"] = tel
		this.Data["admin"] = admin
		this.TplNames = "users.html"
	}else{
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
}

/*********************************************************/
/************函数：UpdateAdmin*****************************/
/************功能：更新管理员的数据**************************/
/********************************************************/
func (this *AdminController)UpdateAdmin(){


	if islogin,_ := this.CheckAdminIsLogin();islogin == true {


		old_tel := this.Ctx.Input.Param(":tel")   //从url中提取参数
		tel := this.GetString("Tel")                //从表单中提取数据
		username := this.GetString("UserName")        //从表单中提取数据
		pw := this.GetString("UserPw")                //从表单中提取数据
		admin := m.Admin{Tel:tel, UserName:username, UserPw:pw}

		if old_tel != "" {

			data := this.GetSession(old_tel)     //获取session
			var mAdminSessionType AdminSessionType
			if data != nil {
				mAdminSessionType = data.(AdminSessionType)
				if mAdminSessionType.IsLogin == true {
					_, err := m.UpdateAdmin(&admin)      //将更新数据写入数据库中
					if err != nil {
						data := SiteResponeType{RespCode:SITE_WRITE_SQL_ERROR, Msg:"写入数据库错误", Data:""}
						this.Data["json"] = &data
						this.ServeJson();
						return
					}
					data := SiteResponeType{RespCode:SITE_SUCCESS, Msg:"更改成功，请刷新页面", Data:""}
					this.Data["json"] = &data
					this.ServeJson();
				}
			}
		}
		data := SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"参数错误", Data:""}
		this.Data["json"] = &data
		this.ServeJson();
		return
	}else{
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
}



/*********************************************************/
/************函数：DeleteAdmins****************************/
/************功能：删除管理员的数据**************************/
/********************************************************/
func (this *AdminController)DeleteAdmins(){
	if islogin,_ := this.CheckAdminIsLogin();islogin == true {
		form := DelTelsType{}                             //创建解析json的变量
		json.Unmarshal(this.Ctx.Input.RequestBody, &form)        //解析json
		tels_len := len(form.Tel)                                //获取要删除的数据的数组大小
		err_tel := make([]string, tels_len)                    //创建数组切片
		fmt.Println("len form", tels_len)
		for _, tel := range form.Tel {
			_, err := m.DelAdminByTel(tel)                     //遍历删除
			if err != nil {
				fmt.Println("err", err)
				err_tel = append(err_tel, tel)                //如果失败则将数据加入失败数组中以便返回
			}
		}
		if len(err_tel) == 0 {                            //全部删除成功
			data := SiteResponeType{RespCode:SITE_SUCCESS, Msg:"", Data:err_tel}
			this.Data["json"] = &data
			this.ServeJson();
			return
		}else {
			data := SiteResponeType{RespCode:SITE_DELETE_ERR, Msg:"删除错误", Data:err_tel}
			this.Data["json"] = &data
			this.ServeJson();
			return
		}
	}else{
		this.Ctx.Redirect(302, "/admin/login")
		return
	}

}
/*********************************************************/
/************函数：DeleteAdmin***************************/
/************功能：删除单个管理员的数据**********************/
/********************************************************/
func (this *AdminController)DeleteAdmin(){
	tel := this.Ctx.Input.Param(":tel")   //从url中提取参数
	del_tel := this.GetString("Tel")      //从表单中提取参数

	if tel != ""{

		data := this.GetSession(tel)     //从session中取出数据
		var mAdminSessionType AdminSessionType
		if data != nil{
			mAdminSessionType = data.(AdminSessionType)
			if mAdminSessionType.IsLogin == true{      //用户已经登入
				admin,_:= m.GetAdminByTel(tel)
				if (admin.Permission&0X01) != 1{
					data := SiteResponeType{RespCode:SITE_PERMISSION_ERR,Msg:"您没有权限",Data:""}
					this.Data["json"] = &data
					this.ServeJson();
					return
				}
				_,err:= m.DelAdminByTel(del_tel)     //删除用户
				if err != nil{
					data := SiteResponeType{RespCode:SITE_WRITE_SQL_ERROR,Msg:"写入数据库错误",Data:""}
					this.Data["json"] = &data
					this.ServeJson();
					return
				}
				data := SiteResponeType{RespCode:SITE_SUCCESS,Msg:"删除成功",Data:""}
				this.Data["json"] = &data
				this.ServeJson();
			}
		}
	}
	data := SiteResponeType{RespCode:SITE_PARA_ERROR,Msg:"参数错误",Data:""}
	this.Data["json"] = &data
	this.ServeJson();
	return

}
/*********************************************************/
/************函数：SysSetting*****************************/
/************功能：返回系统控制页面*************************/
/********************************************************/
func (this *AdminController)SysSetting(){
	tel := this.Ctx.Input.Param(":tel")    //获取url的参数

	if tel == ""{              //tel为空，页面重定向
		this.Ctx.Redirect(302, "/admin/login")
		return
	}else{
		data := this.GetSession(tel)      //获取session
		var mAdminSessionType AdminSessionType
		if data == nil{
			this.Ctx.Redirect(302, "/admin/login")
			return
		}else{
			mAdminSessionType = data.(AdminSessionType)
			if mAdminSessionType.IsLogin == false{      //用户没有登录
				this.Ctx.Redirect(302, "/admin/login")
				return
			}else{
				if((mAdminSessionType.LastDate.Unix() - time.Now().Unix()) > ONEDAY2SEC){    //session超期无效
					this.Ctx.Redirect(302, "/admin/login")
					return
				}
			}
		}
	}

	thresholdValue ,err1:= m.GetThresholdValue()
	particleSize ,err2:= m.GetParticleSize()
	mahine_learn ,err3:= m.GetSysMashineLearn()
	if ( err1 != nil){
		this.Abort("401")
	}
	if ( err2 != nil){
		this.Abort("401")
	}
	if ( err3 != nil){
		this.Abort("401")
	}
	this.Data["thresholdValue"]=thresholdValue
	this.Data["particleSize"]=particleSize
	this.Data["mahine_learn"]=mahine_learn
	this.Data["tel"] = tel
	this.TplNames = "sys-setting.html"
}

/*********************************************************/
/************函数：OnlineDevices**************************/
/************功能：返回在线设备的数据***********************/
/********************************************************/
func (this *AdminController)OnlineDevices(){
	data := GetOnlineDevice()     //获取的在线设备的数据
	fmt.Println("count",data)
	var array_data []DeviceScript
	array_data = make([]DeviceScript,len(data))
	i := 0
	for _,v := range data{
		array_data[i] = v
		i++
	}
	this.Data["json"] = &array_data
	this.ServeJson();
}

/*********************************************************/
/************函数：AdminTelVerifyCode*********************/
/************功能：获取验证码******************************/
/********************************************************/
func (this *AdminController)AdminTelVerifyCode(){
	var tel TelType
	var mAdminSessionType AdminSessionType
	var resp_data AdminRespType
	tel.Tel = this.GetString("Tel")    //获取用户输入的参数
	valid := validation.Validation{}	//进行数据效验
	b, err := valid.Valid(&tel)
	if err != nil {                //检测效验是不是出错
		resp_data = AdminRespType{OPERATION_ERROR, "系统故障"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}
	if !b {    //检测效验是不是出错
		resp_data = AdminRespType{NOT_TEL, "输入的手机号格式有误"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}


	if tel.Tel == ""{   //检测效验是不是出错
		resp_data = AdminRespType{TEL_NULL,TEL_NULL_MSG}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}
	//mAdminSessionType = this.GetSession(tel).(AdminSessionType)
	data := this.GetSession(tel.Tel)  //从session中取出数据

	fmt.Println("data",data)
	y,m,d := time.Now().Date()
	fmt.Println("t",y,m,d)
//
	if data == nil{     //判断数据是否为空，为空则创建数据
		fmt.Println("session null")
		random_code := RandInt(100000,999999)
		mAdminSessionType.LastDate = time.Now()
		mAdminSessionType.Count = 1
		mAdminSessionType.VefifyCode = random_code
		this.SetSession(tel.Tel, mAdminSessionType)
		//random_codes := strconv.FormatInt(int64(random_code),10)
		//msg := "您的验证码是："+random_codes+"。请不要把验证码泄露给其他人。"
		//VerificationCode(msg,tel.Tel)
		fmt.Println("mAdminSessionType",mAdminSessionType)
		resp_data = AdminRespType{SITE_SUCCESS, SUCCESS_MSG}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}else {						//不为空则验证数据
		mAdminSessionType = data.(AdminSessionType)
		mY, mM, mD := mAdminSessionType.LastDate.Date()
		y, m, d := time.Now().Date()
		if (mD == d) {
			if (mM == m) {
				if (mY == y) {
					if mAdminSessionType.Count > DEFAULT_MAX_MSG {     //计算session是否超期
						resp_data = AdminRespType{MAX_MSG, MAX_MSG_MSG}
						this.Data["json"] = &resp_data
						this.ServeJson();
						return
					}else {          //session没有超期
						random_code := RandInt(100000,999999)
						mAdminSessionType.Count += 1
						mAdminSessionType.VefifyCode = random_code
						fmt.Println("mAdminSessionType",mAdminSessionType)
						this.SetSession(tel.Tel, mAdminSessionType)
						//random_codes := strconv.FormatInt(int64(random_code),10)
						//msg := "您的验证码是："+random_codes+"。请不要把验证码泄露给其他人。"
						//VerificationCode(msg,tel.Tel)
						//VerificationCode("您的验证码是：2436。请不要把验证码泄露给其他人。",tel)
						resp_data = AdminRespType{SITE_SUCCESS, SUCCESS_MSG}
						this.Data["json"] = &resp_data
						this.ServeJson();
						return
					}
				}
			}
		}
		random_code := RandInt(100000,999999)
		mAdminSessionType.LastDate = time.Now()
		mAdminSessionType.Count = 1
		mAdminSessionType.VefifyCode = random_code
		this.SetSession(tel.Tel, mAdminSessionType)
		fmt.Println("mAdminSessionType",mAdminSessionType)
		//VerificationCode("您的验证码是：2436。请不要把验证码泄露给其他人。",tel)
		resp_data = AdminRespType{SITE_SUCCESS, SUCCESS_MSG}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}


}


/*********************************************************/
/************函数：AdminTelVerifyCode*********************/
/************功能：验证验证码******************************/
/********************************************************/
func (this *AdminController)CheckVerifyCode(){
	tel := this.GetString("Tel")
	var resp_data AdminRespType

	random_code,err:= this.GetInt("VerifyCode")     //提取用户的输入参数
	if(tel == ""){    //验证号码是不是为空
		resp_data = AdminRespType{SITE_PARA_ERROR,"查询的电话号码有误"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}
	if(err != nil){     //验证验证码是不是正确
		resp_data = AdminRespType{SITE_PARA_ERROR,"空验证码"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}
	//mAdminSessionType := this.GetSession(tel).(AdminSessionType)

	data := this.GetSession(tel)       //从session中获取数据
	if data == nil{
		resp_data = AdminRespType{SITE_PARA_ERROR,"无法验证验证码"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}
	mAdminSessionType := data.(AdminSessionType)   //轮换成想要的格式
	fmt.Println("mAdminSessionType.VefifyCode",mAdminSessionType.VefifyCode)
	//VerificationCode("您的验证码是：2436。请不要把验证码泄露给其他人。",tel)
	if(mAdminSessionType.VefifyCode == int(random_code)){        //测试验证码是否正确
		resp_data = AdminRespType{SITE_SUCCESS,"验证码正确"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}else{
		resp_data = AdminRespType{SITE_VERIFY_CODE,"验证码错误"}
		this.Data["json"] = &resp_data
		this.ServeJson();
		return
	}
			resp_data = AdminRespType{SITE_SUCCESS,"验证码正确"}
			this.Data["json"] = &resp_data
			this.ServeJson();
}

/*********************************************************/
/************函数：SaveParticleSize*************************/
/************功能：保存控制服务器自我学习的时间粒度*************/
/********************************************************/
func (this *AdminController)SaveParticleSize(){
	var resp SiteResponeType
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		particle_size , err := this.GetInt("ParticleSize") //提取用户的输入参数
		fmt.Println("particle_size", particle_size)

		if err != nil {      //用户输入的参数有误
			fmt.Println("err", err)
			resp = SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"输入数据有问题", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
		if particle_size > MAC_PARTICLE_SIZE {   //大于系统设置的最大值
			resp = SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"数据太大，大于"+strconv.Itoa(MAC_PARTICLE_SIZE), Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
		if err = m.SetParticleSize(int(particle_size)); err != nil {   //将数据写入到数据库中
			resp = SiteResponeType{RespCode:SITE_WRITE_SQL_ERROR, Msg:"写入数据有误", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
		resp = SiteResponeType{RespCode:SITE_SUCCESS, Msg:"成功", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
	}else{
		resp = SiteResponeType{RespCode:INVALID_NAME, Msg:"无权限", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}
}
/*********************************************************/
/************函数：SaveThreshold**************************/
/************功能：保存服务器开启自动控制的阀值***************/
/********************************************************/
func (this *AdminController)SaveThreshold(){
	var resp SiteResponeType
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		thread_hold , err := this.GetInt("ThresholdValue")   //提取用户的输入参数
		fmt.Println("thread_hold", thread_hold)

		if err != nil {                                     //用户输入的参数有误
			fmt.Println("err", err)
			resp = SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"输入数据有问题", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
		if thread_hold > MAX_THRESHOLD {                        //大于系统设置的最大值
			resp = SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"数据太大，大于2^64", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
		if err = m.SetThresholdValue(int64(thread_hold)); err != nil {        //将数据写入到数据库中
			resp = SiteResponeType{RespCode:SITE_WRITE_SQL_ERROR, Msg:"写入数据有误", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
		resp = SiteResponeType{RespCode:SITE_SUCCESS, Msg:"成功", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
	}else{
		resp = SiteResponeType{RespCode:INVALID_NAME, Msg:"无权限", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}

}

/*********************************************************/
/************函数：SaveMahineLearn*************************/
/************功能：保存是否开启机器学习的标志位***************/
/********************************************************/
func (this *AdminController)SaveMahineLearn(){
	var resp SiteResponeType
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {

		method := this.Ctx.Input.Method()
		if method == "POST" {
			mSysMashineLearn , err := this.GetBool("SysMashineLearn")  //提取用户的输入参数
			fmt.Println("mSysMashineLearn", mSysMashineLearn)

			if err != nil {         //用户输入的参数有误
				fmt.Println("err", err)
				resp = SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"输入数据有问题", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
			}
			if err = m.SetSysMashineLearn(mSysMashineLearn); err != nil {    //用户输入的参数写入数据库中
				resp = SiteResponeType{RespCode:SITE_WRITE_SQL_ERROR, Msg:"写入数据有误", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
			}
			resp = SiteResponeType{RespCode:SITE_SUCCESS, Msg:"成功", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
	}else{
		resp = SiteResponeType{RespCode:INVALID_NAME, Msg:"无权限", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}
}


/*********************************************************/
/************函数：SaveMahineLearn*************************/
/************功能：保存是否开启机器学习的标志位***************/
/********************************************************/
func (this *AdminController)AddRemoteData(){

	method := this.Ctx.Input.Method()
	if method == "POST" {
		//islogin,_ := true//this.CheckAdminIsLogin()
		islogin := true
		if islogin == true {
			fmt.Println("this.Ctx.Input.RequestBody",string(this.Ctx.Input.RequestBody))

			form := m.RemoteWareHouse{}

			errjson := json.Unmarshal(this.Ctx.Input.RequestBody, &form)
			fmt.Println("errjson",errjson)
			if (errjson != nil) {
//				fmt.Println("errjson",errjson)
				beego.Error("json   Unmarshal err",errjson)
				resp := SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"参数错误", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
				return
			}
			if err := m.AddOfficialRemote(&form, form.User); err != nil {  //将数据加入到数据库中
				resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"数据库执行出错", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
				return
			}
			resp := SiteResponeType{RespCode:SITE_SUCCESS, Msg:"成功", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
		}else{
			resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"无权限", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
		}
	}else{
		//islogin,_ := this.CheckAdminIsLogin()
		islogin := true
		if islogin == true {
			tel := this.Ctx.Input.Param(":tel")  //获取参数
			this.Data["tel"] = tel
			this.TplNames = "add_remote_data.html"
			return
		}else{
			this.Ctx.Redirect(302, "/admin/login")
			return
		}
	}
}

/*********************************************************/
/************函数：GetRemoteList**************************/
/************功能：获取官方遥控器数据的列表******************/
/********************************************************/
func (this *AdminController)GetRemoteList(){
	islogin,_:= this.CheckAdminIsLogin()
	if islogin == true {
		tel := this.Ctx.Input.Param(":tel")
		this.Data["tel"] = tel
		this.TplNames = "show_remotes.html"
		return
	}else{
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
}
/*********************************************************/
/************函数：GetRemoteListJson**************************/
/************功能：获取官方遥控器数据的列表******************/
/********************************************************/
func (this *AdminController)GetRemoteListJson(){
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		result, err := m.GetOfficialRemoteList()  //从数据库中取出所有的官方数据
		if err != nil {
			fmt.Println("err", err)
			resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"数据库执行出错", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
		}
		resp := SiteResponeType{RespCode:SITE_SUCCESS, Msg:"成功", Data:result}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}else{
		resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"无权限", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}
}
/*********************************************************/
/************函数：GetRemoteData**************************/
/************功能：通过ID获取官方遥控器数据******************/
/********************************************************/
func (this *AdminController)GetRemoteData(){
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		obj_id := this.Ctx.Input.Param(":obj_id")  //获取参数
		if obj_id == "" {    //参数为空，表示用户没有输入
			resp := SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"参数错误", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
		}
		result, err := m.GetOfficialRemoteByID(obj_id)
		if err != nil {
			fmt.Println("err", err)
		}
		resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"数据库执行出错", Data:result}
		this.Data["json"] = &resp
		this.ServeJson();
	}else{
		resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"无权限", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
	}
}

/*********************************************************/
/************函数：UpdateRemoteData************************/
/************功能：更新官方遥控器数据************************/
/********************************************************/
func (this *AdminController)UpdateRemoteData() {
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		method := this.Ctx.Input.Method()
		if method == "POST" {
			form := m.RemoteWareHouse{}
			errjson := json.Unmarshal(this.Ctx.Input.RequestBody, &form)
			fmt.Println("errjson",errjson)
			if (errjson != nil) {
				//				fmt.Println("errjson",errjson)
				beego.Error("json   Unmarshal err", errjson)
				resp := SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"参数错误", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
			}
			obj_id := this.Ctx.Input.Param(":obj_id")
			fmt.Println("form", form)

			if err := m.UpdateOfficialRemote(obj_id, form); err != nil {   //更新数据库错误
				resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"数据库执行出错", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
				return
			}
			//
			resp := SiteResponeType{RespCode:SITE_SUCCESS, Msg:"成功", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
		}else {
			obj_id := this.Ctx.Input.Param(":obj_id")
			if obj_id == "" {
				resp := SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"参数错误", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
				return
			}
			result, err := m.GetOfficialRemoteByID(obj_id)
			if err != nil {
				resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"数据库执行出错", Data:""}
				this.Data["json"] = &resp
				this.ServeJson();
				return
			}
			tel := this.Ctx.Input.Param(":tel")
			this.Data["tel"] = &tel
			this.Data["RemoteData"] = &result
			this.TplNames = "update_remote_data.html"
			return
		}
	}else {
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
}

/*********************************************************/
/************函数：SearchRemote****************************/
/************功能：根据RemoteName搜索遥控器数据**************/
/********************************************************/
func (this *AdminController)SearchRemote() {
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		name := this.Ctx.Input.Param(":remote_name")
		if name == "" {
			resp := SiteResponeType{RespCode:SITE_PARA_ERROR, Msg:"参数错误", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
		}
		result, err := m.SearchRemoteByName(name)
		if err != nil {
			fmt.Println("err", err)
		}
		resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"系统搜索失败", Data:result}
		this.Data["json"] = &resp
		this.ServeJson();
	}else{
		resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"成功", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}
}
/*********************************************************/
/************函数：DelRemoteById**************************/
/************功能：删除官方遥控器数据的*********************/
/********************************************************/
func (this *AdminController)DelRemoteById(){
	islogin,_ := this.CheckAdminIsLogin()
	if islogin == true {
		result, err := m.GetOfficialRemoteList()  //从数据库中取出所有的官方数据
		if err != nil {
			fmt.Println("err", err)
		}
		resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"", Data:result}
		this.Data["json"] = &resp
		this.ServeJson();
	}else{
		resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
	}
}

/*********************************************************/
/************函数：DelRemoteById**************************/
/************功能：删除官方遥控器数据的*********************/
/********************************************************/
func (this *AdminController)DelRemotes(){
		if islogin,_ := this.CheckAdminIsLogin();islogin == true {
			form := DelRemotesType{}
			json.Unmarshal(this.Ctx.Input.RequestBody, &form)        //解析json
			objs_len := len(form.ObjectIDs)                                //获取要删除的数据的数组大小
			err_obj := make([]string, objs_len)                    //创建数组切片
			fmt.Println("form", form)
			fmt.Println("objs_len", objs_len)
			for _, object_id := range form.ObjectIDs {
				fmt.Println("object_id",object_id)
				err := m.DelOfficialRemote(object_id)                     //遍历删除
				if err != nil {
					fmt.Println("err", err)
					err_obj = append(err_obj, object_id)                //如果失败则将数据加入失败数组中以便返回
				}
			}
		if len(err_obj) == 0{
			resp := SiteResponeType{RespCode:SITE_OPERATION_ERROR, Msg:"部分数据删除失败", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
		}
			resp := SiteResponeType{RespCode:SITE_SUCCESS, Msg:"删除成功", Data:""}
			this.Data["json"] = &resp
			this.ServeJson();
			return
	}else{
		resp := SiteResponeType{RespCode:INVALID_NAME, Msg:"未登入", Data:""}
		this.Data["json"] = &resp
		this.ServeJson();
	}
}
func (this *AdminController)AddNewApp(){
	tel  := this.Ctx.Input.Param(":tel")
	if islogin,_ := this.CheckAdminIsLogin();islogin == false {
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
	update_info := this.GetString("UpdateInfo")
	AppName := this.GetString("AppName")
	Version := this.GetString("Version")
	fmt.Println("AppName",AppName,"Version","update_info",update_info)
	url := data_url+AppName+"_"+Version+".apk"
	fmt.Println("url",)
	err := this.SaveToFile("APP",url)
	if err != nil{
		fmt.Println("err",err)
		this.Abort("404")
		return
	}
	m.AddNewVersion(AppName ,Version ,update_info ,url )
	this.Redirect("/admin/app_list/"+tel, 302)
}
func (this *AdminController)AddApp(){
	if islogin,_ := this.CheckAdminIsLogin();islogin == false {
		this.Ctx.Redirect(302, "/admin/login")
		return
	}
	tel  := this.Ctx.Input.Param(":tel")
	this.Data["tel"] = tel
	this.TplNames = "add_new_app.html"
}
func (this *AdminController)GetAppList(){
	var resp AppListType
	if islogin,_ := this.CheckAdminIsLogin();islogin == false {
		resp.RespCode = NEED_LOGIN
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}
	list ,count,err:= m.GetVersionList()

	if err != nil{
		resp.RespCode = SITE_OPERATION_ERROR
	}else{
		resp.RespCode = SITE_SUCCESS
		resp.List = list
		resp.Count = count
	}
	this.Data["json"] = &resp
	this.ServeJson();
	return
}
func (this *AdminController)AppList(){
	if islogin,_ := this.CheckAdminIsLogin();islogin == false {
		this.Ctx.Redirect(302, "/admin/login")

		return
	}
	tel  := this.Ctx.Input.Param(":tel")
	this.Data["tel"] = tel
	this.TplNames = "app_list.html"
}


func (this *AdminController)DelAppList(){
	var resp SiteResponeType
	if islogin,_ := this.CheckAdminIsLogin();islogin == false {
		resp = SiteResponeType{RespCode:SITE_DELETE_ERR, Msg:"删除错误", Data:INVALIDS}
		this.Data["json"] = &resp
		this.ServeJson();
		return
	}

	var json_data IdsType

	fmt.Println("this.Ctx.Input.RequestBody",string(this.Ctx.Input.RequestBody))
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &json_data)
	fmt.Println("json_data",json_data)
	fmt.Println("len(json_data.Ids)",len(json_data.Ids))
	if err!= nil{
		resp = SiteResponeType{RespCode:SITE_DELETE_ERR, Msg:"删除错误", Data:INVALIDS}
	}else{
		resp = SiteResponeType{RespCode:SITE_SUCCESS, Msg:"删除成功", Data:INVALIDS}
		for i:=0;i < len(json_data.Ids);i++{
			err2 := m.DeleteById(json_data.Ids[i])
			if err2 != nil{
				resp = SiteResponeType{RespCode:SITE_DELETE_ERR, Msg:"删除成功", Data:INVALIDS}
				break;
			}
		}

	}

	this.Data["json"] = &resp
	this.ServeJson();
	return
}

func (this *AdminController)Test_verify_code(){
	VerificationCode("您的验证码是：123456。请不要把验证码泄露给其他人。如非本人操作，可不用理会！","15928972923")
}


